package com.kvest.scanrecognizer.ui.activity;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import com.kvest.scanrecognizer.R;
import com.kvest.scanrecognizer.contentprovider.ScanRecognizerProviderMetadata;
import com.kvest.scanrecognizer.datastorage.table.RecognizeItemTable;
import com.kvest.scanrecognizer.service.NetworkService;
import com.kvest.scanrecognizer.ui.fragment.ManagerFragment;

/**
 * Created with IntelliJ IDEA.
 * User: Kvest
 * Date: 14.09.13
 * Time: 15:20
 * To change this template use File | Settings | File Templates.
 */
public class ManagerActivity extends BaseActivity implements ManagerFragment.OnActionListener, Runnable {
    private static final int UPDATE_PERIOD = 30000;

    Handler handler = new Handler();

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.fragment_container);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        if (savedState == null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            try {
                transaction.add(R.id.container, new ManagerFragment());
            } finally {
                transaction.commit();
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();

        handler.post(this);
    }

    @Override
    public void onStop() {
        super.onStop();

        handler.removeCallbacks(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu
        getMenuInflater().inflate(R.menu.manager_menu, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_settings) {
            startActivity(new Intent(ManagerActivity.this, SettingsActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onEditName(final long id) {
        //get current name
        String currentName = getNameById(id);

        //create dialog for editing name
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("");
        alert.setMessage(getString(R.string.enter_new_name));
        // Set an EditText view to get user input
        final EditText input = new EditText(this);
        input.setSingleLine(true);
        input.setText(currentName);
        alert.setView(input);
        //set buttons
        alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String newName = input.getText().toString();
                setNameById(id, newName);
            }
        });
        alert.setNegativeButton(android.R.string.cancel, null);
        alert.show();
    }

    @Override
    public void onDownload(String uid, int format) {
        Intent intent = new Intent(this, NetworkService.class);
        intent.putExtra(NetworkService.ACTION_CODE_EXTRA, NetworkService.ACTION_CODE_DOWNLOAD);
        intent.putExtra(NetworkService.UID_EXTRA, uid);
        intent.putExtra(NetworkService.FORMAT_EXTRA, format);
        startService(intent);
    }

    @Override
    public void onSendEmail(String uid, int format) {
        Intent intent = new Intent(this, NetworkService.class);
        intent.putExtra(NetworkService.ACTION_CODE_EXTRA, NetworkService.ACTION_CODE_SEND_EMAIL);
        intent.putExtra(NetworkService.UID_EXTRA, uid);
        intent.putExtra(NetworkService.FORMAT_EXTRA, format);
        startService(intent);
    }

    @Override
    public void onShare(String uid, int format) {
        Intent intent = new Intent(this, NetworkService.class);
        intent.putExtra(NetworkService.ACTION_CODE_EXTRA, NetworkService.ACTION_CODE_SHARE);
        intent.putExtra(NetworkService.UID_EXTRA, uid);
        intent.putExtra(NetworkService.FORMAT_EXTRA, format);
        startService(intent);
    }

    @Override
    public void onDelete(final long id) {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        adb.setTitle(R.string.confirmation);
        adb.setMessage(R.string.delete_file_confirmation);
        adb.setIcon(android.R.drawable.ic_dialog_info);
        adb.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getContentResolver().delete(Uri.withAppendedPath(ScanRecognizerProviderMetadata.RECOGNIZE_ITEMS_URI,
                                                                 Long.toString(id)), null, null);
            }
        });
        adb.setNegativeButton(android.R.string.no, null);
        adb.create().show();
    }

    @Override
    public void run() {
        //start updating
        Intent intent = new Intent(this, NetworkService.class);
        intent.putExtra(NetworkService.ACTION_CODE_EXTRA, NetworkService.ACTION_CODE_UPDATE_STATES);
        startService(intent);

        //start new updating later
        handler.postDelayed(this, UPDATE_PERIOD);
    }

    private String getNameById(long id) {
        Cursor cursor = getContentResolver().query(Uri.withAppendedPath(ScanRecognizerProviderMetadata.RECOGNIZE_ITEMS_URI,
                                                                        Long.toString(id)),
                                                   new String[]{RecognizeItemTable.NAME_COLUMN},
                                                   null, null, null);
        try {
            if (cursor.moveToFirst()) {
                return cursor.getString(cursor.getColumnIndex(RecognizeItemTable.NAME_COLUMN));
            } else {
                return "";
            }
        } finally {
            cursor.close();
        }
    }

    private void setNameById(long id, String name) {
        ContentValues values = new ContentValues(1);
        values.put(RecognizeItemTable.NAME_COLUMN, name);
        getContentResolver().update(Uri.withAppendedPath(ScanRecognizerProviderMetadata.RECOGNIZE_ITEMS_URI,
                                                         Long.toString(id)),
                                    values, null, null);
    }
}
